package com.webshop.DataBase;

import com.webshop.JavaBean.*;
import com.webshop.Utils.ServletOut;
import com.webshop.service.AddressService;
import com.webshop.service.OrderService;
import com.webshop.service.ShopcarService;
import com.webshop.service.UltimateServie;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/DealServlet")
public class DealServlet extends HttpServlet {
    AddressService as = new AddressService();
    ShopcarService ss = new ShopcarService();
    OrderService os = new OrderService();
    UltimateServie us = new UltimateServie();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String method = request.getParameter("method");
        System.out.println(method);
        switch (method) {
            case "submit":
                doSubmit(request, response);
                break;
            case "partShopCar"://部分购物车购买（从最上面的购物车来的）※
                partCar(request, response);
                break;
            case "singleProduct":
                singleProduct(request, response);
                break;
            case "pay":
                pay(request, response);
                break;
        }

    }

    /**
     * 支付流程
     * @param request
     * @param response
     */
    private void pay(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("支付");
        HttpSession session = request.getSession();
        Object temp = session.getAttribute("name");
        String name = String.valueOf(temp);//获得了用户的姓名

        String sum = request.getParameter("sum");//支付的金额（安全问题）
        System.out.println(sum);

        //这里的sum
        String jsondata = request.getParameter("jsondata");
        String addressID = request.getParameter("addressID");

        System.out.println(jsondata);

        /**
         * 需要前台传过来购买的商品详情ID，购买的数量。看来只能用json了。√
         *
         * 需要前台传过来地址的ID
         *
         * 后台需要解析json
         *
         * 生成一个订单号  日期+用户名的hash
         *
         *
         */


        Address address = new Address();
        address = as.selectAddress(addressID);
        System.out.println(address);
        String OrderID = os.bornOrder(name);
        String time = os.backTime();

        double totalprice = Double.valueOf(sum);
        Order order = new Order(OrderID, name, time, address.getAddressee(), address.getAddress(), address.getPhone(), totalprice, 0);
        //可以向主订单表插入
        os.addOrder(order);

        JSONArray jsonArray = JSONArray.fromObject(jsondata);//开始解析json
        List<Goods_attr> goods = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            String ID=  (String.valueOf(jsonArray.getJSONObject(i).getInt("ID"))) ;//拿到了购物车的ID
            int nums=jsonArray.getJSONObject(i).getInt("num") ;//拿到了数量
            //有了详细商品的 ID 和数量，可以更新商品的库存。
            Shopcar shopcar = ss.backShopCar(ID);

            Goods_attr goods_attr = us.backGoodAttr(shopcar.getGoodsAttrID() + "");
            if (goods_attr.getPath() == null) {
                goods_attr.setPath(us.backGood(goods_attr.getProductID()).getMainPic());

            }

           // Goods_attr goods_attr = us.backGoodAttr(ID);
            goods_attr.setStock(goods_attr.getStock() - nums);
            int stock = goods_attr.getStock();
            us.changeStock(ID, stock + "");
            System.out.println(ID+"存货"+stock);

            //当然也需要向详细的order表插入。

            Goods TemoGood = us.backGood(goods_attr.getProductID());


            Detail_order detail_order = new Detail_order(OrderID, goods_attr.getProductname(),
                    goods_attr.getColor(), TemoGood.getMainPic(), goods_attr.getNewPrice(),
                    nums, goods_attr.getNewPrice());
            detail_order.setSumPrice(nums * detail_order.getOnlyPrice());
            System.out.println("详细订单"+detail_order);
            os.addDetailOrder(detail_order);//插入成功
            //跳转到支付页

            System.out.println(detail_order);


        }

        ServletOut.request(request, response, "/Ailiservlet?WIDout_trade_no="+OrderID+"" +
                "&&WIDtotal_amount="+sum+"&&WIDsubject"+name+"");



    }


    /**
     * 单一的购物（从商品详情页进入）
     * @param request
     * @param response
     */
    private void singleProduct(HttpServletRequest request, HttpServletResponse response) {
        String id = request.getParameter("ID");
        Goods_attr goods_attr = us.backGoodAttr(id);
        HttpSession session = request.getSession();
        String name = String.valueOf(session.getAttribute("name"));
        goods_attr.setPath(us.backGood(goods_attr.getProductID()).getMainPic());
        Shopcar shopcar = new Shopcar(name, goods_attr.getProductname(), 1, goods_attr.getPath(), goods_attr.getNewPrice(), goods_attr.getID(), goods_attr.getColor());

        ss.insertservice(shopcar);

        //根据goodsattr的id找到购物车的id
        Shopcar temp=ss.backShopcarDenpendAttrID(id,name);




        List<Shopcar> shopcars = new ArrayList<>();
        shopcars.add(temp);

        List<Address> addresses = as.getUserAddress(name);
        request.setAttribute("address", addresses);
        request.setAttribute("shopcar", shopcars);



        ServletOut.request(request, response, "html/submit.jsp");
    }

    /**
     * 从上方的购物车页面进入
     * 返回的是选中的购物车信息
     * @param request
     * @param response
     */
    private void partCar(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("购物车");
        String jsondata = request.getParameter("jsondata");
        JSONArray jsonArray = JSONArray.fromObject(jsondata);
        System.out.println(jsonArray.toString());
        List<Shopcar> shopcars = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
             String ID=  (String.valueOf(jsonArray.getJSONObject(i).getInt("ID"))) ;//拿到了购物车ID
             int nums=jsonArray.getJSONObject(i).getInt("num") ;//拿到了数量
            Shopcar shopcar = ss.backShopCar(ID);
            shopcar.setNums(nums);
            shopcars.add(shopcar);
        }

        //添加完之后，向submit页面跳转。
        HttpSession session = request.getSession();
        String name = String.valueOf(session.getAttribute("name"));
        List<Address> addresses = as.getUserAddress(name);
        request.setAttribute("address", addresses);

        request.setAttribute("shopcar", shopcars);

        ServletOut.request(request, response, "html/submit.jsp");
    }

    /**
     * 向前台返回全部购物车和个人信息。
     * 在购物车里购买。
     * @param request
     * @param response
     */
    private void doSubmit(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        String name = String.valueOf(session.getAttribute("name"));
        List<Address> addresses = as.getUserAddress(name);
        request.setAttribute("address", addresses);

        List<Shopcar> shopcars = ss.buyfindshop(name);
        request.setAttribute("shopcar", shopcars);



        ServletOut.request(request, response, "html/submit.jsp");

    }



}
